package com.wms.interceptor;

import cn.hutool.core.collection.CollUtil;
import com.wms.utils.JwtUtils;
import com.wms.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @author Yzxxn
 */
@Component
//拦截器是要注册才会生效的
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("token");

        //如果token为空，响应401
        if (ObjectUtils.isEmpty(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //解析token
        Map<String, Object> jwt = JwtUtils.parseJwt(token);
        if (CollUtil.isEmpty(jwt)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //将解析的token中的数据存储到ThreadLocal中
        UserContext.set(jwt);
        //返回true是表示不用拦截请求，请求通过
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();
    }
}
